<template>
  <div>
    <top-nav-bar :applyPageRoute="nowRouteTitle" @back="back"></top-nav-bar>
    <a-spin :spinning="loading">
      <a-card :bordered="false" class="nowPage">
        <p class="module_title">基本信息</p>
        <div style="width: 750px;">
          <a-form-model ref="ruleForm" :model="data" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-model-item label="学习计划标题" prop="title">
              <a-input v-model="data.title" placeholder="请填写学习计划标题,四十字以内" />
            </a-form-model-item>
            <a-form-model-item label="发送班级" prop="class_id" class="sendClasses">
              <a-tree-select v-model="data.class_id" tree-checkable style="width: 100%;" :tree-data="treeData"
                :show-checked-strategy="SHOW_PARENT" placeholder="请选择发送班级" @change="treeChange" />
            </a-form-model-item>
            <a-form-model-item label="截止时间" prop="deadline">
              <a-date-picker showTime style="width: 100%;" v-model="data.deadline" placeholder="请选择截止时间"
                format="YYYY-MM-DD HH:mm" :disabled-date="disabledDate">
                <template slot="renderExtraFooter"></template>
              </a-date-picker>
              <p style="font-size:12px;margin-top:0;line-height:12px;">若设置截止时间,截止前一天20:00,系统将自动提醒未查看学习计划的学员</p>
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-card>
      <a-card :bordered="false" style="margin-top: 25px;">
        <p class="module_title">学习计划详情</p>
        <div style="width: 750px;margin-left:8px;">
          <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-model-item label=" " prop="data.content[0].content" :colon="false">
              <a-textarea v-model="data.content[0].content" :autoSize="{ minRows: 3, maxRows: 6 }" />
            </a-form-model-item>
            <a-form-model-item label=" " :colon="false" v-if="fileArr.length > 0">
              <div class="fileListArr">
                <div v-for="(item, index) in fileArr" :key="index" class="fileEachOne">
                  <img :src="item.content" v-if="item.type == 'picture'" />
                  <video :src="item.content" v-if="item.type == 'video'" controls>你的浏览器暂不支持vedio标签</video>
                  <a class="close_" @click="fileArr.splice(index, 1)">
                    <a-icon type="close" :style="{ fontSize: '16px' }" />
                  </a>
                </div>
              </div>
            </a-form-model-item>
            <a-form-model-item label=" " :colon="false">
              <div class="uploadData" style="width:100%;text-align:center;border:1px dashed #e8e8e8;padding:10px 0;">
                <upload-mp4 @url="getUploadData"></upload-mp4>
              </div>
            </a-form-model-item>
            <a-form-model-item label=" " :colon="false">
              <a-button type="primary" @click="submit('ruleForm')" style="margin-right:10px;">发布学习计划</a-button>
              <a-button @click="back">返回</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import moment from 'moment'

import { homeworkOnceCreate } from '@/api/homework'
import topNavBar from '@/components/topNavBar/topNavBar'
import { TreeSelect } from 'ant-design-vue'
import { studentList } from '@/api/student'
import { classList } from '@/api/class'
import uploadMp4 from '@/components/uploadIMG_AVI'
import { string } from 'clipboard'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
// const SHOW_PARENT = TreeSelect.SHOW_ALL
//选择班级控件

export default {
  name: 'Single',
  components: {
    topNavBar,
    uploadMp4
  },

  data() {
    return {
      children: [],
      nowRouteTitle: '发布学习计划',
      Isclass: [],
      rules: {
        title: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        class_id: [{ required: true, message: '请选择发送班级/学生' }],
        deadline: [{ required: true, message: '请选择截至日期', trigger: 'change' }],
        // 添加 content[0].content 的验证规则
        'data.content[0].content': [
          { required: true, message: '请输入学习计划详情', trigger: 'blur' },
          { min: 5, message: '学习计划详情至少需要5个字符', trigger: 'blur' }
        ]
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      data: {
        title: undefined,
        class_id: undefined,
        deadline: undefined,
        content: [
          {
            type: 'text',
            content: ''
          }
        ]
      },
      fileArr: [],
      //zhouData
      sumClasses: [],
      //树选择
      value: [],
      treeData: [],
      SHOW_PARENT,
      loading: false
    }
  },
  created() {
    this.nowRouteTitle = this.$route.meta.title
    let date = moment()
    this.data.title = moment(date).format('YYYY-MM-DD') + '学习计划'
    this.showClass()
  },
  mounted() { },
  watch: {},
  methods: {
    disabledDate(current) {
      return current && current < moment().startOf('day')
    },
    //获取上传资源返回的内容
    submit(formName) {

      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true
          let params = JSON.parse(JSON.stringify(this.data))

          if (params.content[0].content == '') {
            this.$message.warning('请填写学习计划详情')
            this.loading = false
            return
          }

          if (this.fileArr.length > 0) {
            let data = JSON.parse(JSON.stringify(this.fileArr))
            data.forEach(val => {
              params.content.push(val)
            })
          }
          let choiceClass = JSON.parse(JSON.stringify(this.choiceClass))
          params.save_type = 1
          params.school_id = this.$store.state.user.school
          params.member_arr = choiceClass
          params.deadline = moment(params.deadline).format('YYYY-MM-DD HH:mm')
          // params.content.forEach(item=>{
          //   if(item.type=='text'){
          //     item.content=item.content.replace(/\r\n/g,"<br>")
          // 	  item.content=item.content.replace(/\n/g,"<br>"); 
          //   }
          // })
          homeworkOnceCreate(params)
            .then(res => {
              this.$message.success('发布学习计划成功')
              this.loading = false
              this.back()
            })
            .catch(err => {
              this.$message.error(err.data.message || '发布学习计划失败')
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    getUploadData(data, type) {
      let arr = ['video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov', 'video/mp4']
      if (arr.indexOf(type) !== -1) {
        this.fileArr.push({
          type: 'video',
          content: data
        })
        this.btnLoading = false
      } else {
        this.fileArr.push({
          type: 'picture',
          content: data
        })
        this.btnLoading = false
      }
    },
    //选择班级
    treeChange(value) {
      let arr = []
      value.forEach(val => {
        if (typeof val == 'string') {
          let data = this.strSubstr(val)
          if (arr.length > 0) {
            let num = 0
            arr.forEach(item => {
              if (item.class_id == data.class_id) {
                item.student_ids.push(data.student_ids[0])
                num++
              }
            })
            if (num == 0) {
              arr.push(data)
            }
          } else {
            arr.push(data)
          }
        } else {
          arr.push({ class_id: val, student_ids: [0] })
        }
      })
      this.choiceClass = arr
    },
    //树选择截取$前后的字符
    strSubstr(obj) {
      let index = obj.lastIndexOf('$')
      let last = obj.substring(index + 1, obj.length)
      let first = obj.substring(0, index)
      return { class_id: Number(first), student_ids: [Number(last)] }
    },
    onLoadData(treeNode) {
      const { id } = treeNode.dataRef
    },
    back() {
      this.$router.go(-1)
    },
    showClass() {
      // 树状数据
      classList({ school_id: this.$store.state.user.school, pageSize: 999999, status: 1 })
        .then(res => {
          this.$data.sumClasses = res.data
          this.$data.treeData = this.$data.sumClasses
          this.$data.treeData.map((item, index) => {
            this.$data.treeData[index].title = item.name
            this.$data.treeData[index].key = item.id
            this.$data.treeData[index].value = item.id
            this.$data.treeData[index].children = []
            if (item.student.length > 0) {
              item.student.map((cItem, cIndex) => {
                this.$data.treeData[index].children[cIndex] = {}
                this.$data.treeData[index].children[cIndex].title = cItem.name
                this.$data.treeData[index].children[cIndex].key = item.id + '$' + cItem.id
                this.$data.treeData[index].children[cIndex].value = item.id + '$' + cItem.id
              })
            }
          })
        })
        .catch(err => {
          this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
        })
    }
  }
}
</script>
<style lang="less" scoped>
.fileListArr {
  display: flex;
  flex-wrap: wrap;
  border: 1px dashed #e8e8e8;
  padding: 10px 10px 0;

  .fileEachOne {
    margin-right: 12px;
    margin-bottom: 15px;
    padding: 10px 10px 5px;
    width: 122px;
    height: 122px;
    overflow: hidden;
    position: relative;
    border-radius: 4px;

    .close_ {
      position: absolute;
      right: 0px;
      top: -12px;
      display: none;
    }

    img,
    video {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 4px;
    }
  }

  .fileEachOne:hover {
    .close_ {
      display: block;
    }
  }
}

.module_title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  line-height: 22px;
  margin-bottom: 15px;
}

.uploadComponent {
  width: 600px;
  margin: 10px 0 0 100px;
  border: 1px dashed rgb(165, 165, 165);
  display: flex;
  justify-content: space-around;
  padding: 10px;
}

.nowPage {
  padding: 0 8px;
}

.sendJob {
  width: 100%;
  margin-top: 10px;
  margin-left: 100px;
}
</style>
